package com.vm.fragment;

import java.util.List;

import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.vm.activity.LoginActivity;
import com.vm.activity.OrderConfirmActivity;
import com.vm.commons.CurrentGoods;
import com.vm.commons.CurrentUser;
import com.vm.commons.VMConst;
import com.vm.db.GoodsCollectionDao;
import com.vm.db.ShoppingCartDao;
import com.vm.model.Goods;
import com.vm.model.GoodsCollection;
import com.vm.model.ShoppingCart;
import com.vm.utils.JsonUtils;
import com.vm.utils.SingleRequestQueue;
import com.wwtscapp.apk.R;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("InflateParams")
public class GoodsFragment extends BaseFragment {
	private View view;
	TextView imgbtn_sub1;
	TextView imgbtn_add1;
	TextView tv_market_price;
	TextView tv_goodsName;
	TextView tv_total_price;
	EditText tv_num1;
	Float price;
	String num;
	String goodsId;
	Button btn_buy;
//	Button btn_add_to_cart;
	Goods goods1 = new Goods();
	List<GoodsCollection> list;
	List<ShoppingCart> list2;
	ShoppingCartDao sDao;
	ShoppingCart shoppingCart;
	private RequestQueue mQueue;
	/** 标志位，标志已经初始化完成 */
	private boolean isPrepared;

	/** 是否已被加载过一次，第二次就不再去请求数据了 */
	// private boolean mHasLoadedOnce;
	@Override
	protected void lazyLoad() {
		// TODO Auto-generated method stub

		if (!isPrepared || !isVisible) {
			return;
		}
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (view == null) {
			view = inflater.inflate(R.layout.goods_details, null);
		} else {
			// 缓存的rootView需要判断是否已经被加过parent
			// 如果有parent需要从parent删除
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}
		isPrepared = true;
		init();

		goodsId = getArguments().getString("goodsId");
		String url = VMConst.REQUEST_URL + "goodsdetail?goodsId=" + goodsId;
		mQueue = SingleRequestQueue.getRequestQueue(getActivity());
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null,
				new Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						Goods goods = new Goods();
						goods = JsonUtils.jsonToBean(arg0, Goods.class);
						if(goods.getName()!=null){
						tv_goodsName.setText(goods.getName());
						}
						tv_market_price.setText("¥"
								+ Float.toString(goods.getPrice()));
						price = goods.getPrice();
						tv_total_price.setText("¥"
								+ Float.toString(price * Integer.parseInt(num)));
						CurrentGoods.GODOSPRICE = goods.getPrice();
						CurrentGoods.GOODSID = goods.getId();
						CurrentGoods.GOODSIMG = goods.getImageUrl();
						CurrentGoods.GOODSNAME = goods.getName();
						goods1 = goods;
					}
				}, null);
		mQueue.add(jsonObjectRequest);
		initNum();
		lazyLoad();

		return view;

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	// 初始化控件
	public void init() {
		new GoodsCollection();
		new GoodsCollectionDao(getActivity());
		sDao = new ShoppingCartDao(getActivity());
		shoppingCart = new ShoppingCart();
//		btn_add_to_cart = (Button) view.findViewById(R.id.btn_add_to_cart);
	
		tv_market_price = (TextView) view.findViewById(R.id.tv_market_price);
		tv_goodsName = (TextView) view.findViewById(R.id.tv_goodsName);
		tv_total_price = (TextView) view.findViewById(R.id.tv_total_price);
		imgbtn_sub1 = (TextView) view.findViewById(R.id.imgbtn_sub1);
		imgbtn_add1 = (TextView) view.findViewById(R.id.imgbtn_add1);
		imgbtn_sub1.setOnClickListener(num_listener);
		imgbtn_add1.setOnClickListener(num_listener);
		btn_buy = (Button) view.findViewById(R.id.btn_buy);
//		btn_add_to_cart = (Button) view.findViewById(R.id.btn_add_to_cart);
		btn_buy.setOnClickListener(btn_ClickListener);
//		btn_add_to_cart.setOnClickListener(shoppingCartListener);
		tv_num1 = (EditText) view.findViewById(R.id.tv_num1);
		tv_num1.addTextChangedListener(textWatcher);
		tv_num1.setOnClickListener(btn_ClickListener);
		tv_num1.clearFocus();
		tv_num1.setFocusable(false);
	}

	// 设置EditText的数值，判断是否为1
	public void initNum() {
		num = tv_num1.getText().toString();

		if (num.equals("1")) {
			imgbtn_sub1.setTextColor(getActivity().getResources().getColor(
					R.color.sub1));
		} else {
			imgbtn_sub1.setTextColor(getActivity().getResources().getColor(
					R.color.sub));
		}
	}

	OnClickListener btn_ClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_buy:
				if (CurrentUser.USERID != null) {
					Intent intent = new Intent(getActivity(),
							OrderConfirmActivity.class);
					intent.putExtra("goods", goods1);
					intent.putExtra("num", num);
					CurrentGoods.NUM = Integer.parseInt(num);
					startActivity(intent);
				} else {
					Toast toast = Toast.makeText(getActivity(), "请先登录",
							Toast.LENGTH_SHORT);
					toast.show();
					Intent intent = new Intent(getActivity(),
							LoginActivity.class);
					startActivity(intent);
				}
				break;
			case R.id.tv_num1:
				tv_num1.setFocusable(true);
				tv_num1.setFocusableInTouchMode(true);
				tv_num1.requestFocus();
			}
		}

	};
	OnClickListener shoppingCartListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (sDao.ifExits(goodsId)) {
				Toast toast = Toast.makeText(getActivity(), "该商品已经加入购物车了哦",
						Toast.LENGTH_SHORT);
				toast.show();
			} else {
				shoppingCart.setGoodsId(goodsId);
				shoppingCart.setImageUrl(CurrentGoods.GOODSIMG);
				shoppingCart.setName(CurrentGoods.GOODSNAME);
				shoppingCart.setPrice(CurrentGoods.GODOSPRICE);
				shoppingCart.setNumber(1);
				sDao.insert(shoppingCart);
				Toast toast = Toast.makeText(getActivity(), "加入购物车成功",
						Toast.LENGTH_SHORT);
				toast.show();
			}
		}

	};
	OnClickListener num_listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			// 判断EditText的内容是否为正整数，不是设为1
			if (tv_num1.getText() != null) {
				for (int j = 0; j < num.length(); j++) {
					if (!(num.charAt(j) >= 48 && num.charAt(j) <= 57)
							|| Integer.parseInt(num) == 0) {
						System.out.println("您输入的不是正整数!请重新输入.");
						tv_num1.setText("1");
						num = "1";
					}
				}
			} else {
				tv_num1.setText("1");
				num = "1";
			}
			switch (v.getId()) {
			case R.id.imgbtn_sub1:
				if (num.equals("1")) {

				} else {
					int i = Integer.parseInt(num);
					i--;
					// String.valueOf(i);
					tv_num1.setText(String.valueOf(i));
				}
				initNum();
				tv_total_price.setText("¥"
						+ Float.toString(price * Integer.parseInt(num)));

				break;
			case R.id.imgbtn_add1:
				int i = Integer.parseInt(num);
				i++;
				tv_num1.setText(String.valueOf(i));
				initNum();
				tv_total_price.setText("¥"
						+ Float.toString(price * Integer.parseInt(num)));

				break;
			}

		}

	};
	private TextWatcher textWatcher = new TextWatcher() {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			// tv_num1.setCursorVisible(false);
			initNum();
			if (tv_num1.getText() != null) {
				for (int j = 0; j < num.length(); j++) {
					if ((num.charAt(j) >= 48 && num.charAt(j) <= 57)
							&& !(Integer.parseInt(num) == 0)) {
						tv_total_price
								.setText("¥"
										+ Float.toString(price
												* Integer.parseInt(num)));
					}
				}
			} else {
				tv_num1.setText("1");
			}
		}

	};

}